// 与文件上传相关的中间件
const fs = require('node:fs')
const fileService = require('../service/file.service')
const {
    AVATAR_REQUIRED,
    AVATAR_FORMAT_ERROR,
    AVATAR_SIZE_100KB_EXCEED
} = require('../error/errorType')
const { localUpload, ossUpload } = require('../utils/upload')
const { server } = require('../env')
const isLocal = server.staticInLocal

const uploadAvatar = isLocal ? localUpload.single('avatar') : ossUpload.single('avatar')

const verifyAvatar = async (ctx, next) => {
    const { file } = ctx.request
    // 判断有无该文件
    if (!file) {
        return ctx.app.emit('error', new Error(AVATAR_REQUIRED), ctx)
    }

    const { mimetype, size } = file
    // 判断文件格式是否合法
    if (mimetype != 'image/jpeg' && mimetype != 'image/png') {
        return ctx.app.emit('error', new Error(AVATAR_FORMAT_ERROR), ctx)
    }
    // 判断文件是否超出指定大小
    if (size > 100 * 1024) {
        return ctx.app.emit('error', new Error(AVATAR_SIZE_100KB_EXCEED), ctx)
    }

    // 到这里说明文件符合所有条件 => 能够安全上传和更新相关数据库表
    ctx.avatar = file
    ctx.isLocal = isLocal
    await next()
}

function existInLocal(filePath, filename) {
    return new Promise((resolve, reject) => {
        fs.access(filePath, (err) => {
            if (err) resolve(false)
            else resolve(true)
        })
    })
}

// 用于访问静态资源的中间件
const verifyStatic = async (ctx, next) => {
    const { filename } = ctx.request.params
    let [ fileInfo ] = await fileService.getFileInfoByName(filename)
    let exist = await existInLocal('./static', filename)
    console.log('exist: ', exist)
    if (fileInfo) {
        ctx.fileInfo = fileInfo
    } else {
        ctx.fileInfo = {
            filename: 'IMG_NOT_FOUND.jpg',
            mimetype: 'image/jpeg',
        }
    }
    await next()
}

module.exports = {
    verifyAvatar,
    uploadAvatar,
    verifyStatic,
}